package com.common;

import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ImgCodeBuilderUtil {
    public static final String RANDOM_CODE_KEY = "random_validate_code_key";// 放到session中的key
    private static final Random random = new Random();
    private static final String randString = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";// 随机产生的字符串

    private static final int imgWidth = 106;// 图片宽
    private static final int imgHeight = 33;// 图片高
    private static final int numberOfLine = 0;// 干扰线数量
    private static final int numberOfChar = 4;// 随机产生字符数量

    private static final String[] fontArray = {"Fixedsys", "Times New Roman"};

    /*
     * 获得字体
     */
    private static Font obtainFont() {
        return new Font(fontArray[1], Font.CENTER_BASELINE, 20);
    }

    /**
     * 生成随机图片
     */
    public static void generateValidateCodeAndOutput(HttpServletRequest request,
                                                     HttpServletResponse response) {
        HttpSession session = request.getSession();
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        g.setFont(obtainFont());

        // 设置图片背景颜色
        g.setColor(new Color(220, 220, 220));
        g.fillRect(0, 0, imgWidth, imgHeight);

        // 设置图片边框颜色
        // g.setColor(new Color(0, 0, 0));
        // g.drawRect(0, 0, imgWidth - 1, imgHeight - 1);

        // 绘制干扰线
        for (int i = 0; i < numberOfLine; i++) {
            drawLine(g);
        }
        // 绘制随机字符
        String randomString = "";
        for (int i = 1; i <= numberOfChar; i++) {
            randomString = drawString(g, randomString, i);
        }
        session.removeAttribute(RANDOM_CODE_KEY);
        session.setAttribute(RANDOM_CODE_KEY, randomString);
        g.dispose();
        try {
            response.setHeader("P3P", "CP=CAO PSA OUR");
            ImageIO.write(image, "JPEG", response.getOutputStream());// 将内存中的图片通过流动形式输出到客户端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 绘制字符串
     */
    private static String drawString(Graphics g, String randomString, int i) {
        g.setFont(obtainFont());
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        String randomChar = String.valueOf(getRandomString(random.nextInt(randString.length())));
        randomString += randomChar;
//        g.translate(random.nextInt(2), random.nextInt(2));
        g.drawString(randomChar, 20 * i, 23);
        return randomString;
    }

    /*
     * 绘制干扰线
     */
    private static void drawLine(Graphics g) {
        int x0 = random.nextInt(imgWidth);
        int y0 = random.nextInt(imgHeight);
        int x0_ = random.nextInt(13);
        int y0_ = random.nextInt(15);
        g.drawLine(x0, y0, x0 + x0_, y0 + y0_);
    }

    /*
     * 获取随机的字符
     */
    private static String getRandomString(int index) {
        return String.valueOf(randString.charAt(index));
    }

    /**
     * 校验验证码
     *
     * @return
     */
    public static boolean validVCode(HttpServletRequest request, String code) {
        if (StringUtils.isBlank(code)) {
            return false;
        }
        HttpSession session = request.getSession();
        String codeInSession = (String) session.getAttribute(RANDOM_CODE_KEY);
        if (StringUtils.isBlank(codeInSession)) {
            return false;
        }
        if (!code.toUpperCase().equals(codeInSession.toUpperCase())) {
            return false;
        }
        session.removeAttribute(RANDOM_CODE_KEY);
        return true;
    }
}
